package com.howard.tools.ldap;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;



public class LdapHelper {
	private static final String INITIAL_CONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
	private static final String LDAP_URL = "ldap://localhost";
	private static final String LDAP_PORT = "389";
	private static final String LDAP_ROOT = "dc=howard,dc=com";
	private static final String LDAP_USR = "cn=admin,dc=howard,dc=com";
	private static final String LDAP_PWD = "abug";
	
	
	public static void testLdap(){
		Hashtable<String,String> env = new Hashtable<String,String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY); 
		env.put(Context.PROVIDER_URL, LDAP_URL + ":" + LDAP_PORT + "/" + LDAP_ROOT); 
		env.put(Context.SECURITY_PRINCIPAL, LDAP_USR); 
		env.put(Context.SECURITY_CREDENTIALS, LDAP_PWD);
		DirContext ctx = null;
		try {
			ctx = new InitialDirContext(env);
			System.out.println("认证成功"); 
		}   
	   catch (javax.naming.AuthenticationException e) {
		   e.printStackTrace();
		   System.out.println("认证失败");   
	    }
		catch (Exception e) {
			System.out.println("认证出错：");
			e.printStackTrace();
		}	
		if (ctx != null) {
			try {
				ctx.close();
			}
			catch (NamingException e) {
				//ignore
			}
		}   
	}
	
	public static void main(String[] args) {

		try {
			long start = System.currentTimeMillis();
			testLdap();
			System.out.println("finished, takes(ms):" + (System.currentTimeMillis() - start));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
